package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo8ExactlyOnce {
    public static void main(String[] args) throws Exception {
        /*
         * 1、从kafka中读取数据
         * 2、在flink中对数据做处理，非聚合计算处理
         * 3、将处理结果保存到kafka中
         */

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //1、从kafka中读取数据
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                .setTopics("lines")
                .setGroupId("Demo8ExactlyOnce")
                .setStartingOffsets(OffsetsInitializer.latest())
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        DataStream<String> lines = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka source");

        //2、在flink中对数据做处理，非聚合计算处理
        DataStream<String> words = lines.flatMap((line, collect) -> {
            for (String word : line.split(",")) {
                collect.collect(word);
            }
        }, Types.STRING);

        DataStream<String> filters = words.filter(word -> !"".equals(word));


        Properties properties = new Properties();
        //指定事务超时时间，不能大于15分钟
        properties.setProperty("transaction.timeout.ms", String.valueOf(5 * 60 * 1000));

        //3、将处理结果保存到kafka中
        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                //指定而外的参数
                .setKafkaProducerConfig(properties)
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        //指定topic
                        .setTopic("words")
                        //指定序列化类
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build()
                )
                //数据处理的语义
                .setDeliverGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
                .build();

        filters.sinkTo(kafkaSink);

        env.execute();
        /*
         * kafka-console-consumer.sh --bootstrap-server  master:9092,node1:9092,node2:9092 --from-beginning --isolation-level read_committed  --topic words
         */



    }
}
